<template>
  <div class="discuss-pull-box">
    <h3 class="discuss-top">讨论区</h3>
    <div class="msg-box"
         ref="msgBox">
      <div v-for="(msg,idx) in msgList"
           :key="idx">
        <p v-show="msg.from == nickName"
           class="msg-item me">
          <span style="float: right;">
            :{{ msg.from }}
          </span>
          <span class="user-msg">
            {{ msg.content }}
          </span>
        </p>
        <p v-show="msg.from != nickName"
           class="msg-item">
          <span style="float: left;">
            {{ msg.from }}:
          </span>
          <span class="from-msg">
            {{ msg.content }}
          </span>
        </p>
      </div>
    </div>
    <div class="chat-box">
      <div class="header">
        <span id="sender">发送方: {{ nickName }}</span>
        <button @click="showEmoji"
                style="font-size: 24px;">😀</button>
      </div>
      <div class="content"
           @click="contentBoxClick">
        <span id="edit"
              ref="editBox"
              @focus="moveCursorToEnd"
              contenteditable="true">
        </span>
        <button id="send"
                @click="sendMsg">发送</button>
      </div>
      <!-- 表情列表 -->
      <div class="emoji-box"
           ref="emojibox">
        <p>&#127800;</p>
        <p>&#127801;</p>
        <p>&#127802;</p>
        <p>&#127803;</p>
        <p>&#127804;</p>
        <p>&#127805;</p>
        <p>&#128512;</p>
        <p>&#128513;</p>
        <p>&#128514;</p>
        <p>&#128515;</p>
        <p>&#128516;</p>
        <p>&#128517;</p>
        <p>&#128518;</p>
        <p>&#128519;</p>
        <p>&#128520;</p>
        <p>&#128521;</p>
        <p>&#128522;</p>
        <p>&#128523;</p>
        <p>&#128524;</p>
        <p>&#128525;</p>
        <p>&#128526;</p>
        <p>&#128527;</p>
        <p>&#128528;</p>
        <p>&#128529;</p>
        <p>&#128530;</p>
        <p>&#128531;</p>
        <p>&#128532;</p>
        <p>&#128533;</p>
        <p>&#128534;</p>
        <p>&#128535;</p>
        <p>&#128536;</p>
        <p>&#128537;</p>
        <p>&#128538;</p>
        <p>&#128539;</p>
        <p>&#128540;</p>
        <p>&#128541;</p>
        <p>&#128542;</p>
        <p>&#128543;</p>
        <p>&#128544;</p>
        <p>&#128545;</p>
        <p>&#128546;</p>
        <p>&#128547;</p>
        <p>&#128548;</p>
        <p>&#128549;</p>
        <p>&#128550;</p>
        <p>&#128551;</p>
        <p>&#128552;</p>
        <p>&#128553;</p>
        <p>&#128554;</p>
        <p>&#128555;</p>
        <p>&#128556;</p>
        <p>&#128557;</p>
        <p>&#128558;</p>
        <p>&#128559;</p>
        <p>&#128560;</p>
        <p>&#128561;</p>
        <p>&#128562;</p>
        <p>&#128563;</p>
        <p>&#128564;</p>
        <p>&#128565;</p>
        <p>&#128566;</p>
        <p>&#128567;</p>
        <p>&#127925;</p>
        <p>&#127926;</p>
        <p>&#127927;</p>
        <p>&#127928;</p>
        <p>&#127929;</p>
        <p>&#127936;</p>
        <p>&#127937;</p>
        <p>&#127938;</p>
        <p>&#127942;</p>
        <p>&#127943;</p>
        <p>&#127944;</p>
        <p>&#127945;</p>
        <p>&#127951;</p>
        <p>&#127952;</p>
        <p>&#127953;</p>
        <p>&#127954;</p>
        <p>&#127955;</p>
        <p>&#128068;</p>
        <p>&#128069;</p>
        <p>&#128070;</p>
        <p>&#128071;</p>
        <p>&#128072;</p>
        <p>&#128073;</p>
        <p>&#128074;</p>
        <p>&#128075;</p>
        <p>&#128076;</p>
        <p>&#128077;</p>
        <p>&#128078;</p>
        <p>&#128079;</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "chatBox",
  props: {
    liveId: {
      type: String
    },
    IsEnd: {
      type: Boolean
    },
    PubOver: {
      type: Boolean
    },
  },
  watch: {
    PubOver: {
      handler (newval, oldval) {
        if (newval) {
          if (this.ws) {
            this.ws.send(JSON.stringify({
              userId: this.userId,
              from: this.nickName,
              to: this.liveId,
              text: "SignPub",
              date: this.$tools.getNow()
            }))
          }
        }
      }
    },
    liveId: {
      handler (newval, oldval) {
        this.roomId = newval;
        // console.log("roomID: ",newval);
      },
      immediate: true
    },
    IsEnd: {
      handler (newval, oldval) {
        if (newval && this.ws) {
          this.ws.send(JSON.stringify({
            userId: "System",
            from: this.nickName,
            to: this.liveId,
            text: "EndBye",
            date: this.$tools.getNow()
          }))
        }
      },
      immediate: true
    }
  },
  data () {
    return {
      text: '',
      msgBox: null,
      headImg: null,
      userId: null,
      nickName: "",
      roleId: null,
      roomId: null,
      show: false,
      timer: null,
      ws: null,
      sign: null,
      msgList: []
    }
  },
  created () {
    this.getLocalInfo();
  },
  mounted () {
    this.initDom();
    this.initWebsocket();
  },
  beforeDestroy () {
    this.ws = null;
    clearInterval(this.timer);
  },
  methods: {
    getLocalInfo () {
      let info = sessionStorage.getItem("userInfo");
      if (info && info !== "") {
        let obj = JSON.parse(info);
        // console.log("chatBox: USER-INFO：", obj);
        this.userId = obj.userid;
        this.headImg = obj.avatar;
        this.nickName = obj.username;
        if (obj.roleid) {
          this.roleId = obj.role.roleid;
        }
      }
    },
    initDom () {
      var list = this.$refs.emojibox.children;
      for (let i = 0; i < list.length; i++) {
        list[i].addEventListener('click', (e) => {
          e.stopPropagation();
          e.preventDefault();
          let txt = e.target.innerText;

          this.text = this.$refs.editBox.innerHTML + txt;
          this.$refs.editBox.innerHTML = this.text;
          console.log(this.text)

          this.$refs.emojibox.style.display = 'none';
          console.log(txt);
          this.$refs.editBox.focus();
        })
      }
      this.msgBox = this.$refs.msgBox;
    },
    moveCursorToEnd () {
      const spanElement = this.$refs.editBox;
      const range = document.createRange();
      const sel = window.getSelection();
      range.selectNodeContents(spanElement);
      range.collapse(false);
      sel.removeAllRanges();
      sel.addRange(range);
    },
    showEmoji () {
      if (!this.show) {
        this.$refs.emojibox.style.display = 'block';
        this.show = true;
      } else {
        this.$refs.emojibox.style.display = 'none';
        this.show = false;
      }
    },
    contentBoxClick () {
      this.$refs.emojibox.style.display = 'none';
      this.$refs.editBox.focus();
    },
    initWebsocket () {
      if (typeof WebSocket != 'undefined') {
        this.ws = new WebSocket(`ws://localhost:8088/websocket/${this.nickName}/${this.roomId}/${this.userId}`)

        this.ws.onopen = (evt) => {
          this.$message.success("链接建立成功");
          this.timer = setInterval(() => {
            try {
              this.ws.send("ping");
            } catch (err) {
              this.$message.error(err);
            }
          }, 5000);
        }

        this.ws.onmessage = (event) => {
          if (event.data === "Pong") {
            return;
          }

          let msg = JSON.parse(event.data);
          // console.log(msg);
          if ("EndBye" == msg.text) {
            this.$emit('stopPlay');
            return;
          }
          if (msg.text === "SignPub") {
            this.$emit("beginSign");
          }
          this.msgList.push({
            from: msg.from,
            content: msg.text
          })
          this.$nextTick(() => {
            this.msgBox.scrollTop = this.msgBox.scrollHeight + 20;
          });
        }

        this.ws.onclose = (event) => {
          this.$message.error(event)
          clearInterval(this.timer);
        }

        this.ws.onerror = (err) => {
          this.$message.error(err)
          clearInterval(this.timer);
          this.initWebsocket();
        }
      } else {
        this.$message.error("当前浏览器不支持Websocket,请更换浏览器");
      }
    },
    sendMsg () {
      this.text = this.$refs.editBox.innerText;
      this.ws.send(JSON.stringify({
        userId: this.userId,
        from: this.nickName,
        to: this.liveId,
        text: this.text,
        date: this.$tools.getNow()
      }))

      this.msgList.push({
        from: this.nickName,
        content: this.text
      })

      this.$nextTick(() => {
        this.msgBox.scrollTop = this.msgBox.scrollHeight + this.$refs.editBox.offsetHeight;
      });
      console.log(this.$refs.msgBox.scrollHeight);
      this.$refs.editBox.innerHTML = '';
      this.text = '';
    }
  }
}
</script>

<style scoped lang="scss">
.discuss-pull-box {
  width: 100%;
  height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  .discuss-top {
    color: #fff;
    padding: 15px 0;
    background-color: #5a687a;
  }
  .msg-box {
    width: 300px;
    height: 400px;
    overflow-y: auto;
    background-color: #e8e8e8;
    box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);
    scroll-behavior: smooth;
    margin: 0px auto;
    .msg-item {
      padding-left: 6px;
      text-align: left;
      height: fit-content;
      padding-bottom: 20px;
      .user-msg {
        display: inline-block;
        width: fit-content;
        color: #000;
        border-radius: 5px;
        background-color: rgb(47, 255, 82);
        max-width: 200px;
        margin: 3px 0px 16px;
        padding: 8px;
        position: relative;
        text-align: left;
        right: 10px;
        top: 20px;
      }
      .from-msg {
        display: inline-block;
        width: fit-content;
        padding: 8px;
        max-width: 200px;
        background-color: #fff;
        border-radius: 5px;
        margin: 3px 0px;
        position: relative;
        left: 10px;
        top: 20px;
      }
    }
    .msg-item ::after {
      content: '';
      clear: both;
    }
    .me {
      color: #14a9da;
      padding-right: 6px;
      text-align: right;
    }
  }

  .chat-box {
    width: 300px;
    height: 260px;
    margin: 0px auto 0;
    box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);
    position: relative;
    .header {
      width: 300px;
      height: 50px;
      line-height: 50px;
      background-color: #f5f5f5;
      position: relative;
    }
    .emoji-box {
      position: absolute;
      left: 0px;
      top: 50px;
      width: 300px;
      height: 260px;
      background-color: #ddd;
      overflow-y: auto;
      display: none;
    }
    .emoji-box p {
      float: left;
      width: 34px;
      height: 34px;
      text-align: center;
      line-height: 34px;
      font-size: 26px;
      margin: 3px;
      cursor: pointer;
    }
    .emoji-box p:hover {
      background-color: #fff;
    }
    .content {
      width: 300px;
      height: 210px;
      overflow-y: auto;
    }
    .header button {
      position: absolute;
      right: 5px;
      top: 7px;
    }
    #edit {
      float: left;
      text-align: left;
      margin-left: 8px;
      padding-left: 6px;
      outline: none;
    }
    #send {
      position: absolute;
      width: 60px;
      height: 30px;

      bottom: 10px;
      right: 10px;
    }
  }
}
</style>